package memory

import (
	"errors"
	"fmt"
	"sync"

	"gitee.com/gomaster/book-library/entity"
)

type MemoryBook struct{}

// 图书管理内存操作 key: ibsn
var bookMap = make(map[string]*entity.BookInfo)

// key: bookName, value: count
var bookStoreMap = make(map[string]int)
var bookLock sync.Mutex

// BookAdd 图书增加. 当前只支持一本一本的添加
func (m *MemoryBook) BookAdd(bk *entity.BookInfo) error {
	if _, ok := bookMap[bk.IBSN]; ok {
		fmt.Printf("图书已经存在，ibsn:%s", bk.IBSN)
		return errors.New("book exist already")
	}

	bookMap[bk.IBSN] = bk
	bookLock.Lock()
	count, ok := bookStoreMap[bk.IBSN]
	if !ok {
		bookStoreMap[bk.IBSN] = 1
	} else {
		count += 1
		bookStoreMap[bk.IBSN] = count
	}
	bookLock.Unlock()
	return nil
}

// BookGet 图书查询
func (m *MemoryBook) BookGet(ibsn string) *entity.BookInfo {
	bk, ok := bookMap[ibsn]
	if !ok {
		fmt.Printf("图书不存在")
		return nil
	}
	return bk
}

// BookDel 图书删除
func (m *MemoryBook) BookDel(ibsn string) error {
	bookInfo, ok := bookMap[ibsn]
	if !ok {
		return nil
	}
	if bookInfo.Status == entity.BookStatusLend {
		fmt.Printf("书籍借阅中，不能删除")
		return errors.New("book is lending, cannot be delete")
	}
	bookLock.Lock()
	delete(bookMap, ibsn)
	bookStoreMap[ibsn]--
	bookLock.Unlock()
	return nil
}

// BookUpdate 图书更新
func (m *MemoryBook) BookUpdate(ibsn string, bk *entity.BookInfo) error {
	memBook, ok := bookMap[ibsn]
	if !ok {
		fmt.Printf("图书不存在，无法更新")
		return errors.New("book does not exist")
	}
	if memBook.Status == entity.BookStatusLend {
		fmt.Printf("当前书籍已借出，")
		return errors.New("当前书籍已借出")
	}
	bookMap[ibsn] = bk
	return nil
}

// BookList 查询图书列表
func (m *MemoryBook) BookList() []*entity.BookInfo {
	// TODO 待实现
	return []*entity.BookInfo{}
}
